import router from './router'
// import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // getToken from cookie
import store from './store'
NProgress.configure({ showSpinner: false })// NProgress configuration

const whiteList = ['/login', '/regist'] // 不重定向白名单
// 跳转之前执行的钩子函数
router.beforeEach(async(to, from, next) => {
  console.log('to', to)
  console.log('from', from)
  NProgress.start()
  if (getToken()) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (store.getters.routers.length === 0) {
        await store.dispatch('GetRouters').then(res => { // 拉取路由信息
          router.addRoutes(res)
          next({ ...to, replace: true })
        }).catch(() => {
          store.dispatch('FedLogOut').then(() => {
            next({ path: '/' })
          })
        })
      } else {
        next()
        // router.addRoutes(store.getters.routers)
        // next({ ...to, replace: true })
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next(`/login?redirect=${to.path}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

// 跳转之后执行的钩子函数
router.afterEach(() => {
  NProgress.done() // 结束Progress
})
